import React, { useState } from 'react';
import { Form, Input, List, message, Modal } from 'antd';
import { revisePass } from '@/services/user';
import md5 from 'js-md5'
import { connect } from 'umi';
import { ConnectState } from '@/models/connect';

type Unpacked<T> = T extends (infer U)[] ? U : T;

const passwordStrength = {
  strong: <span className="strong">强</span>,
  medium: <span className="medium">中</span>,
  weak: <span className="weak">弱 Weak</span>,
};

const SecurityView: React.FC = (props) => {
  const [modalVisible, setModalVisible] = useState(false); //控制 Modal 的显示与隐藏：
  const handleNewActivityClick = () => {
    setModalVisible(true);
  };
  const [form] = Form.useForm();
  const handleModalCancel = () => {
    form.resetFields(); // 将表单重置为空
    setModalVisible(false); // 关闭表单
  };
  const handleModalOk = () => {
    revisePass({oldPassword:md5(form.getFieldValue("oldPassword")), newPassword:md5(form.getFieldValue("newPassword"))}).then((response)=>{
      console.log(response)
      if (response.code === '200'){
        message.success("密码修改成功，请重新登录")
        form.resetFields(); // 将表单重置为空
        setModalVisible(false); // 关闭表单
        const { dispatch } = props;
        if (dispatch) {
          dispatch({
            type: 'login/logout',
          });
        }
      }else {
        message.error("密码修改失败"+response.result)
      }
    })
  };
  const getData = () => [
    {
      title: '账户密码',
      description: (
        <>
          当前密码强度：
          {passwordStrength.strong}
        </>
      ),
      actions: [
        <a
          onClick={() => {
            handleNewActivityClick();
          }}
          key="Modify"
        >
          修改
        </a>,
      ],
    },
    // {
    //   title: '密保手机',
    //   description: `已绑定手机：138****8293`,
    //   actions: [<a key="Modify">修改</a>],
    // },
    // {
    //   title: '邮箱',
    //   description: `已绑定邮箱：ant***sign.com`,
    //   actions: [<a key="Modify">修改</a>],
    // },
  ];

  const data = getData();
  return (
    <>
      <Modal title="修改密码" visible={modalVisible} onCancel={handleModalCancel} onOk={handleModalOk}>
        <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          <Form.Item
            label="原始密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入原始密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度不能小于6位' },
              { pattern: /^(?=.*[0-9])(?=.*[a-zA-Z]).{6,}$/, message: '密码必须包含字母和数字，并且长度不少于6位' }
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirmPassword"
            rules={[
              { required: true, message: '请输入再次输入新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次输入的密码不一致');
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
      <List<Unpacked<typeof data>>
        itemLayout="horizontal"
        dataSource={data}
        renderItem={(item) => (
          <List.Item actions={item.actions}>
            <List.Item.Meta title={item.title} description={item.description} />
          </List.Item>
        )}
      />
    </>
  );
};

export default connect(({ user }: ConnectState) => ({
  user: user,
}))(SecurityView);
